package com.neulogistics.contrib.usercenter.infrastructure.persistence.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neulogistics.contrib.usercenter.domain.model.aggregate.User;
import com.neulogistics.contrib.usercenter.domain.repository.IUserRepository;
import com.neulogistics.contrib.usercenter.infrastructure.persistence.converter.UserEntityPOConverter;
import com.neulogistics.contrib.usercenter.infrastructure.persistence.orm.po.UserPO;
import com.neulogistics.contrib.usercenter.infrastructure.persistence.orm.service.IUserPOService;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class UserRepository implements IUserRepository {
    @Resource
    IUserPOService userPOService;

    @Override
    public void save(User user) {
        UserPO userPO = UserEntityPOConverter.entityToPO(user);
        userPOService.saveOrUpdate(userPO);
        user.setUserId(userPO.getUserId());
    }

    @Override
    public User findById(Integer id) {
        UserPO userPo = userPOService.getById(id);
        User user = UserEntityPOConverter.POToEntity(userPo);
        return user;
    }

    @Override
    public void deleteById(Integer id) {
        userPOService.removeById(id);
    }

    @Override
    public User findByUsername(String userName) {
        LambdaQueryWrapper<UserPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPO::getUsername, userName);
        UserPO userPO = userPOService.getOne(queryWrapper);
        User user = UserEntityPOConverter.POToEntity(userPO);
        return user;
    }
}
